package org.tamal.jsf;

import java.util.ResourceBundle;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.tamal.Constants;

/**
 * This will validate whether the password is strong or not.
 * @author Tamal Kanti Nath
 */
@FacesValidator("EmailValidator")
public final class EmailValidator implements Validator {

    private static final Logger log = Logger
            .getLogger("org.tamal.jsf.EmailValidator");

    @Override
    public void validate(FacesContext context, UIComponent component,
            Object value) {
        String email = (String) value;
        if (isValid(email)) {
            return;
        }
        ResourceBundle rb = context.getApplication().getResourceBundle(context,
                Constants.MSG);
        String summary = rb.getString("EmailValidator.summary");
        summary = String.format(summary, component.getClientId(), value);
        String detail = rb.getString("EmailValidator.detail");
        detail = String.format(detail, component.getClientId(), value);
        throw new ValidatorException(new FacesMessage(
                FacesMessage.SEVERITY_ERROR, summary, detail));
    }

    /**
     * Validate email address against JavaMail parser.
     * @param emailId Email id
     * @return true if valid
     */
    public static boolean isValid(String emailId) {
        if (emailId == null || emailId.isEmpty()) {
            return false;
        }
        InternetAddress[] emails = null;
        try {
            emails = InternetAddress.parse(emailId);
        } catch (AddressException e) {
            log.info(e.toString());
            return false;
        }
        for (InternetAddress email : emails) {
            boolean valid = email.getAddress().matches("[\\w\\.\\-_]+@[\\w\\.\\-]+\\.\\w+");
            if (!valid) {
                log.info("Invalid email: " + email);
                return false;
            }
        }
        return true;
    }
}
